package com.msblearn.C_014;

import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * ForkJoinPool
 * WorkStealingPool:每个线程都有单独的队列，当 一个线程执行完它队列的任务了，而另一个线程的任务还有很多，
 * 它会从另一个线程的队列末尾拿一个线程过来执行。
 * 优点：灵活
 * 当被其他线程执行（Poll）方法的时候是加锁了的。
 */
public class T07_WorkStealingPool {
    public static void main(String[] args) throws IOException {
        ExecutorService service = Executors.newWorkStealingPool();
        System.out.println(Runtime.getRuntime().availableProcessors());

        service.execute(new R(1000));
        service.execute(new R(2000));
        service.execute(new R(2000));
        service.execute(new R(2000));
        service.execute(new R(2000));

        System.in.read();
    }

    static class R implements Runnable {
        int time;

        R(int time) {
            this.time = time;
        }

        @Override
        public void run() {
            try {
                TimeUnit.MILLISECONDS.sleep(time);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(time + "  " + Thread.currentThread().getName());
        }
    }
}
